package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.dto.AlertDataPageReqDto;
import com.zzyl.nursing.dto.AlertDataHandlerDto;
import com.zzyl.nursing.vo.AlertDataVo;
import com.zzyl.system.mapper.SysUserMapper;
import com.zzyl.system.service.impl.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.service.IAlertDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


/**
 * 报警数据Service业务层处理
 * 
 * @author laoYe
 * @date 2025-11-01
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserServiceImpl sysUserServiceImpl;

    /**
     * 分页查询报警数据
     * 
     * @param dto 报警数据主键
     * @return 报警数据
     */


    @Override
    public TableDataInfo<AlertDataVo> selectAlertDataPage(AlertDataPageReqDto dto) {
        Page<AlertData> page = Page.of(dto.getPageNum(), dto.getPageSize());

        LambdaQueryWrapper<AlertData> lambdaQuery = new LambdaQueryWrapper<>();

        // 设备名称（精确搜索）
        if (StringUtils.hasText(dto.getDeviceName())) {
            lambdaQuery.eq(AlertData::getDeviceName, dto.getDeviceName());
        }


        // 开始报警时间（大于等于）
        if (dto.getStartTime() != null) {
            lambdaQuery.ge(AlertData::getCreateTime, dto.getStartTime());
        }

        // 结束报警时间（小于等于）
        if (dto.getEndTime() != null) {
            lambdaQuery.le(AlertData::getCreateTime, dto.getEndTime());
        }

        // 状态（0：待处理，1：已处理）
        if (dto.getStatus() != null) {
            lambdaQuery.eq(AlertData::getStatus, dto.getStatus());
        }

        // 按创建时间降序排序
        lambdaQuery.orderByDesc(AlertData::getCreateTime);

        // 3. 执行分页查询
        IPage<AlertData> iPage = this.page(page, lambdaQuery);

        List<AlertDataVo> vos = iPage.getRecords().stream().map(alertData -> {
            AlertDataVo vo = BeanUtil.toBean(alertData, AlertDataVo.class);
            vo.setNickname(alertData.getDeviceName());
            return vo;
        }).collect(Collectors.toList());


        // 封装返回结果
        TableDataInfo<AlertDataVo> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setTotal(iPage.getTotal());
        tableDataInfo.setRows(vos);
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("请求成功");

        return tableDataInfo;

    }

    /**
     * 分页查询报警数据列表
     * 
     * @param alertData 报警数据
     * @return 报警数据
     */
    @Override
    public List<AlertData> selectAlertDataList(AlertData alertData) {
        return alertDataMapper.selectAlertDataList(alertData);
    }

    /**
     * 新增报警数据
     * 
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     * 
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData) {
        return updateById(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     * 
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     * 
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 处理报警数据
     * @param dto
     */
    @Override
    public void handleAlertData(AlertDataHandlerDto dto) {
        //获取处理人ID
        Long userId = UserThreadLocal.get();
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        lambdaUpdate().eq(AlertData::getId, dto.getId())
                .set(AlertData::getProcessingResult, dto.getProcessingResult())
                .set(AlertData::getProcessingTime, dto.getProcessingTime())
                .set(AlertData::getStatus,1)
                .set(AlertData::getProcessorId, userId)
                .set(AlertData::getProcessorName, sysUser.getNickName())
                .set(AlertData::getUpdateTime, LocalDateTime.now())
                .update();
    }

    @Override
    public AlertData selectAlertDataById(Long id) {
        return getById(id);
    }
}
